import ruxOpenAp from '../../utils/requZhanfuAi'
import { zhanfuApiUrl } from '../../config/zhanfuAiApiUrl'
import ApiError from '../../error/ApiError'
import ApiErrorNames from '../../error/ApiErrorNames'
import AiOrder from '../../model/AiOrder'
import Shop from '../../model/shop'
import redis from '../../dbHelper/redis'
import AiUser from '../../model/AiUser'
import DlyadminAiFuncsConfig from '../../model/dlyadminAiFuncsConfig'

function fomateData(data, infoDataUSer) {
	let getQuery = {}
	Object.keys(data).forEach((key) => {
		const infoData = data[key]
		if (infoData.min || infoData.max) {
			if (infoDataUSer[key] < infoData.min || infoDataUSer[key] > infoData.max) {
				throw new ApiError(ApiErrorNames.selectInDengtData(`参数${key}需在${infoData.min} ~ ${infoData.max}之间`))
			}
		}
		if (infoData.required && !infoDataUSer[key]) {
			throw new ApiError(ApiErrorNames.nogetText(key))
		}
		if (!infoData.required && !infoDataUSer[key]) {
			if (!infoData.default) {
				if (infoData.yilai && !infoDataUSer[infoData.yilai]) {
					let contentIndert = `参数${key}或${infoData.yilai}必填一项；`
					throw new ApiError(ApiErrorNames.selectInDengtData(contentIndert))
				}
			} else {
				infoDataUSer[key] = infoData.default
			}
		}
		if (infoData.type === 'object') {
			fomateData(infoData.query, infoDataUSer[key])
		}
		if (infoDataUSer[key] != undefined) {
			getQuery[key] = typeof infoDataUSer[key] == 'object' ? JSON.stringify(infoDataUSer[key]) : infoDataUSer[key]
		}
	})
	return getQuery
}
async function junkerUserScoer(getUserJifen, getUseConter) {
	if (getUserJifen.remainScore < getUseConter.use_points) {
		throw new ApiError(ApiErrorNames.NO_JIFEN)
	} else {
		// 扣除用户积分
		await AiUser.updateOne({ _id: getUserJifen._id }, {
			$inc: {
				remainScore: -getUseConter.use_points
			}
		})
		getUseConter.status = '1'
		await redis.set(`${getUserJifen._id}_${getUseConter._id}`, JSON.stringify(getUseConter))
		return true
	}
}

// 扣除积分算法
async function getAiJifen(jwtuserinfo, addOrderDataInfo) {
	console.log('addOrderDataInfo', addOrderDataInfo)
	if (addOrderDataInfo.similarCharge == '1') {
		addOrderDataInfo.use_points = addOrderDataInfo.image_num * addOrderDataInfo.use_points
	}

	console.log('getAiJifen', jwtuserinfo, addOrderDataInfo)
	const getUserJifen = await AiUser.findOne({ _id: jwtuserinfo._id })
	let shopData
	if (addOrderDataInfo.shop_id) {
		shopData = await Shop.findOne({ _id: addOrderDataInfo.shop_id, aiUserId: getUserJifen._id })
	}

	console.log('getUserJifen', getUserJifen)
	if (getUserJifen.remainScore >= addOrderDataInfo.use_points) {
		// 扣除用户积分
		const derii = await AiUser.updateOne({ _id: getUserJifen._id }, {
			$inc: {
				remainScore: -addOrderDataInfo.use_points
			}
		})
		addOrderDataInfo.status = '1'
		await redis.set(`${getUserJifen._id}_${addOrderDataInfo._id}`, JSON.stringify(addOrderDataInfo))
		console.log('扣除本来的', derii)
		return {
			code: 1,
			msg: '购买的积分够扣'
		}
	}
	if (getUserJifen.remainScore > 0) {
		let shoutermins = addOrderDataInfo.use_points - getUserJifen.remainScore
		console.log('shoutermins', shoutermins)
		if (getUserJifen.remainSendScore >= shoutermins) {
			// 扣除用户积分
			const sendrefos = await AiUser.updateOne({ _id: getUserJifen._id }, {
				remainScore: 0,
				$inc: {
					remainSendScore: -shoutermins
				}
			})
			console.log('扣除本来家送的', sendrefos)
			return {
				code: 1,
				msg: '送的跟自己买的合起来够'
			}
		}
		// 这里可以看店铺情况
		const shopScoerdData = await getShopJifen(getUserJifen.remainScore)
		console.log('店铺扣情况', shopScoerdData)
		return shopScoerdData
	}
	// 看送的情况
	if (getUserJifen.remainSendScore >= addOrderDataInfo.use_points) {
		// 扣除用户积分
		const sendrefos = await AiUser.updateOne({ _id: getUserJifen._id }, {
			$inc: {
				remainSendScore: -addOrderDataInfo.use_points
			}
		})
		console.log('送的够扣', sendrefos)
		return {
			code: 1,
			msg: '送的够扣'
		}
	}
	const uterDater = await getShopJifen()
	console.log('店铺扣情况', uterDater)
	return uterDater


	async function getShopJifen() {
		if (shopData) {
			console.log('这个店铺有绑定 可以检查是否有积分可以被扣')
			if (getUserJifen.remainSendScore > 0) {
				let outershop = addOrderDataInfo.use_points - (getUserJifen.remainScore || 0) - (getUserJifen.remainSendScore || 0)
				if (shopData.aiRemainScore >= outershop) {
					const sendrefos = await AiUser.updateOne({ _id: getUserJifen._id }, {
						remainScore: 0,
						remainSendScore: 0
					})
					const shopderii = await Shop.updateOne({ shop_id: shopData.shop_id }, {
						$inc: {
							aiRemainScore: -outershop
						}
					})
					console.log('扣除店铺积分', sendrefos, shopderii)
					return {
						code: 1,
						msg: '店铺+送的 + 自己够扣'
					}
				}
				return {
					code: 0,
					msg: '店铺+送的 + 自己不够扣'
				}
			}
			// 扣除用户积分
			if (shopData.aiRemainScore >= addOrderDataInfo.use_points) {
				let outershop = addOrderDataInfo.use_points - (getUserJifen.remainScore || 0) - (getUserJifen.remainSendScore || 0)
				const sendrefos = await AiUser.updateOne({ _id: getUserJifen._id }, {
					remainScore: 0,
					remainSendScore: 0
				})
				const cbhbegr = await Shop.updateOne({ shop_id: shopData.shop_id }, {
					$inc: {
						aiRemainScore: -outershop
					}
				})
				console.log('扣除店铺积分', cbhbegr)
				return {
					code: 1,
					msg: '店铺够扣'
				}
			}
			return {
				code: 0,
				msg: '店铺不够扣'
			}
		}
		console.log('这个店铺没有绑定')
		return {
			code: 0,
			msg: '这个店铺没有绑定,没得扣'
		}


	}


}

class Ai {
	static async aiRspRs(ctx) {
		// console.log('2222',  ctx.request.body)
		const { api = '', query = null } = ctx.request.body
		if (!api || !query) {
			throw new ApiError(ApiErrorNames.NoParamsData)
		}
		const apiConfig = zhanfuApiUrl[api]
		if (!apiConfig) {
			throw new ApiError(ApiErrorNames.noGetAiApi)
		}

		const jumpCheackApi = ['rux.open.ai.image.style', 'rux.open.ai.image.getModelPromptProperties', 'rux.open.ai.chat.completionCreate']
		if (!jumpCheackApi.includes(api)) {
			// 非法调用
			throw new ApiError(ApiErrorNames.ERR_JUMP_CHEACK_API)
			// throw new ApiError(ApiErrorNames.noGetAiApi)
		}

		const onjectKeys = fomateData(apiConfig.query, query)
		// console.log('onjectKeys', onjectKeys)
		const ruxOpenApiResev = await ruxOpenAp(onjectKeys, api)
		// 保存对应记录
		ctx.body = ruxOpenApiResev
	}
	static async AiRsq(ctx) {
		const aiUserData = JSON.parse(ctx.request.header.jwtuserinfo)
		// console.log('AiRsq', ctx.request.body)
		if (!ctx.request.body) {
			throw new ApiError(ApiErrorNames.NoParamsData)
		}
		const { api = '', query = null, ai_order_id = '' } = ctx.request.body
		if (!api || !query) {
			throw new ApiError(ApiErrorNames.NoParamsData)
		}
		if (typeof query !== 'object') {
			throw new ApiError(ApiErrorNames.queryTypeErr)
		}
		const apiConfig = zhanfuApiUrl[api]
		if (!apiConfig.jumpOredr && !ai_order_id) {
			throw new ApiError(ApiErrorNames.NoParamsData)
		}
		const redisIoData = await redis.get(`${aiUserData._id}_${ai_order_id}`)
		let getData
		if (!redisIoData) {
			// 没有就需要查询数据库
			const getOrderData = await AiOrder.findOne({ _id: ai_order_id, ai_user_id: aiUserData._id })
			if (!getOrderData) {
				throw new ApiError(ApiErrorNames.NO_REF_ORDER)
			}
			getData = getOrderData
		} else {
			getData = JSON.parse(redisIoData)
		}
		if (!apiConfig) {
			throw new ApiError(ApiErrorNames.noGetAiApi)
		}

		// const getUserJifen = await AiUser.findOne({ _id: aiUserData._id })
		if (getData.status == '0') {
			const addconter = await getAiJifen(aiUserData, getData)
			if (addconter.code == 1) {
				getData.status = '1'
				await redis.set(`${aiUserData._id}_${ai_order_id}`, JSON.stringify(getData))
			}
		}
		const redisIoDataRefos = await redis.get(`${aiUserData._id}_${ai_order_id}`)
		// console.log('redisIoDataRefos', redisIoDataRefos)
		const redisIoDataRefosJson = JSON.parse(redisIoDataRefos)
		if (redisIoDataRefosJson.status != '1') {
			throw new ApiError(ApiErrorNames.ORSER_ERR_STATUS)
		}

		const onjectKeys = fomateData(apiConfig.query, query)
		const ruxOpenApiResev = await ruxOpenAp(onjectKeys, api)
		// console.log('ruxOpenApiResev', ruxOpenApiResev)
		if (!ruxOpenApiResev.errorCode) {
			console.log('api', api)
			if (ruxOpenApiResev.data.data.code !== 200) {
				ctx.body = ruxOpenApiResev
				return
			}
			if (api === 'rux.open.ai.image.create3') {
				await AiOrder.updateOne({ _id: ai_order_id }, {
					white_id: ruxOpenApiResev.data.data.data.id
				})
			}
			if (api !== 'rux.open.ai.image.create3' && /create*/.test(api)) {
				await AiOrder.updateOne({ _id: ai_order_id }, {
					create_id: ruxOpenApiResev.data.data.data.id,
					progress: '1'
				})
			}

		} else {
			throw new ApiError(ApiErrorNames.SERVER_ERR)
		}
		// 保存对应记录
		ctx.body = ruxOpenApiResev
	}
	static async cretedOrder(ctx) {
		const aiUserData = JSON.parse(ctx.request.header.jwtuserinfo)

		const {
			shop_id = '',
			func_type = '',
			func_name = '',
			sys_type = '',
			image_num = 4,
			info_key = '',
			goods_id = ''
		} = ctx.request.body || {}
		// console.log('ctx.request.body', ctx.request.body)
		if (!func_type || !func_name || !sys_type) {
			throw new ApiError(ApiErrorNames.NoParamsData)
		}

		const getUseConter = await DlyadminAiFuncsConfig.findOne({ type: func_type, status: '1' })

		// console.log('getUseConter', getUseConter)
		// return
		if (!getUseConter) {
			throw new ApiError(ApiErrorNames.NO_FUNC_TYPE)
		}
		const addOrderDataInfo = {
			func_type,
			func_name,
			sys_type,
			ai_user_id: aiUserData._id,
			use_points: getUseConter.charge == '0' ? 0 : getUseConter.num,
			charge: getUseConter.charge,
			similarCharge: getUseConter.similarCharge,
			linenum: getUseConter.linenum,
			progress: func_type == 4 ? '1' : '0',
			image_num,
			info_key,
			goods_id
			// status: func_type == 4 ? '1' : '0',
		}
        // const newSaves = await AiOrder.create(addOrderDataInfo)
        // ctx.body = newSaves
        // return 

		if (shop_id) {
			const shopData = await Shop.findOne({ shop_id, aiUserId: aiUserData._id })
			// console.log('shopData', shopData)
			if (!shopData) {
				// 店铺不存在 或未绑定
				throw new ApiError(ApiErrorNames.SHOP_ID_NOT_EXIST_OR_NOT_BING)
			}
			// shopData.aiRemainScore = 100
			// await shopData.save()
			// 判断店铺是否已经订购付费
			addOrderDataInfo.shop_id = shopData._id
			// 这里需要加上商品ID
		}
		if (func_type == 4) {
			// 这里扣除积分
			const addconter = await getAiJifen(aiUserData, addOrderDataInfo)
			// console.log('扣除积分结果', addconter)
			if (addconter.code == 1) {
				addOrderDataInfo.status = '1'
			} else {
				addOrderDataInfo.status = '0'
			}
			// 修改支付状态
			const aiOrderData = await AiOrder.create(addOrderDataInfo)
			// 这里返回MD5加密
			ctx.body = aiOrderData
			return
		}

		const aiOrderDataser = await AiOrder.create(addOrderDataInfo)
		// console.log('aiOrderData', aiOrderData)
		await redis.set(`${aiUserData._id}_${aiOrderDataser._id}`, JSON.stringify(aiOrderDataser))
		ctx.body = aiOrderDataser
		// const aiOrderData =
	}
	static async getAiOrders(ctx) {
		const aiUserData = JSON.parse(ctx.request.header.jwtuserinfo)
		const { page = 1, pageSize = 10 } = ctx.request.query
		const aiOrderData = await AiOrder.find({ ai_user_id: aiUserData._id })
			// 关联查询shop字段
			.populate('shop_id')
			.sort({ createTime: -1 })
			.limit(pageSize * 1)
			.skip((page - 1) * pageSize)
		const total = await AiOrder.find({ ai_user_id: aiUserData._id }).countDocuments()
		ctx.body = {
			list: aiOrderData,
			total
		}
	}
	static async saveCreted(ctx) {
		const { id = '', image_list = '' } = ctx.request.body || {}
		try {
			const aiOrderData = await AiOrder.findOne({ _id: id })
			if (!aiOrderData) {
				throw new ApiError(ApiErrorNames.SYSTEM_ERROR)
			}
			aiOrderData.progress = '2'
			aiOrderData.image_list = image_list
			await aiOrderData.save()
			ctx.body = aiOrderData
		} catch (error) {
			throw new ApiError(ApiErrorNames.SYSTEM_ERROR)
		}

	}
}

export default Ai
